package com.sunronsoft.mind.map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.ehcache.CacheKit;

/**
 * @author Sunron
 **/
public class AuthInterceptor implements Interceptor {
    
    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        String actionKey = inv.getActionKey();

        if ((controller instanceof IndexController && actionKey.equals("/")) || checkActionKey(actionKey)) {
            inv.invoke();
        } else {
            // 判断用户是否登录
            String sessionId = controller.getSession().getId();
            Kv record = CacheKit.get("authorizationCache", sessionId);
            String token = StrKit.isBlank(controller.getHeader("token"))
                            ? controller.getPara("token")
                            : controller.getHeader("token");

            if (null != record) {
                if (StrKit.notBlank(record.getStr("token")) && record.getStr("token").equalsIgnoreCase(token)) {
                    inv.invoke();
                } else {
                    controller.redirect("/");
                }
            } else if (StrKit.notBlank(token)) {
                Kv data = Kv.by("code", 1002).set("msg", "请重新登录");
                controller.renderJson(data);
            } else {
                controller.redirect("/");
            }
        }
    }

    private boolean checkActionKey(String actionKey) {
        String[] keys = new String[] {
                "login",
                "captcha",
                "chart",
                //"main",
                "mind",
                "register",
                "logout"
        };
        for (String key : keys) {
            if (actionKey.contains(key)) return true;
        }
        return false;
    }
}
